package javaweb.oa;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import javaweb.oa.Utils.DBUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

@WebServlet(value={"/user/login","/user/exit"})
public class UserServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String servletPath = request.getServletPath();
        if("/user/login".equals(servletPath)){
            doLogin(request,response);
        }else if("/user/exit".equals(servletPath)){
            doExit(request,response);
        }

    }

    private void doExit(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException{

        HttpSession session = request.getSession(false);
        if(session!=null){
            session.invalidate();
        }
        //删除cookie
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            Arrays.stream(cookies)
                    .filter(cookie->cookie.getName().equals("username")||cookie.getName().equals("password"))
                    .forEach(cookie->{
                        cookie.setPath(request.getContextPath());
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    });
        }
        response.sendRedirect(request.getContextPath());

    }

    protected void doLogin(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //验证用户名和密码是否正确
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 连接数据库验证用户名和密码
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        boolean flag = false;

        try{
            conn = DBUtil.getConnection();
            String sql = "select * from user where username=? and password=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs = ps.executeQuery();
            if(rs.next()){
                flag = true;
            }

        }catch(SQLException e){
            e.printStackTrace();
        }finally{
            DBUtil.close(conn,ps,rs);
        }

        // 登录成功/登录失败
        if(flag){
            // 成功，跳转到用户列表外面
            HttpSession session = request.getSession();
            session.setAttribute("username",username);

            // 登录成功了，并且用户确实选择了“十天内免登录”功能
            String f = request.getParameter("f");
            if("1".equals(f)){
                // 创建Cookie对象
                Cookie cookie = new Cookie("username",username);
                Cookie cookie2 = new Cookie("password",password);//真实情况下是加密的
                // 设置cookie的有效时间
                cookie2.setMaxAge(60*60*24*10);
                cookie.setMaxAge(60*60*24*10);
                //设置cookie的path
                cookie.setPath(request.getContextPath());
                cookie2.setPath(request.getContextPath());

                response.addCookie(cookie);
                response.addCookie(cookie2);
            }
            response.sendRedirect(request.getContextPath() + "/dept/list");

        }else{
            response.sendRedirect(request.getContextPath() + "/loginerror.html");
        }

    }
}
